package com.cheng.example.atguigu.practice.proVscon.v2;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


//lock锁
public class Test {

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    private LinkedList list = new LinkedList();
    private int max = 10;


    public void pro(int i) {
        lock.lock();
        try {
            while (list.size() >= 10) {
                condition.await();
            }
            list.add(list);
            System.out.println("生产:" + i);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public void con(int i) {
        lock.lock();
        try {
            while (list.size() <= 0) {
                condition.await();
            }
            list.pop();
            System.out.println("消费:" + i);
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        Test test = new Test();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.con(i);
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                test.pro(i);
            }
        }).start();


    }
}
